<template>
    <section>
        <el-dialog
                title="任务派发"
                :visible.sync="visible"
                :value="value"
                width="500px"
        >

            <el-form
                    :model="task"
                    :rules="rules"
                    ref="taskForm"
            >
                <el-form-item
                        label="任务名称"
                        :label-width="labelWidth"
                        prop="name"
                >
                    <span style="font-size: 15px;font-weight: bold">{{ template.name }}</span>
                </el-form-item>
                <el-form-item
                        label="角色分组" v-if="template.templateSort&&template.templateSort.value!='FIXED'"
                        :label-width="labelWidth"
                        prop="roleGroup"
                >
                    <el-select
                            v-model="task.roleGroup" @change="groupChange"
                            placeholder="请选择角色分组"
                    >
                        <el-option
                                v-for="(item,index) in groups"
                                :key="index"
                                :label="item.groupName"
                                :value="item.groupId"
                        />
                    </el-select>
                </el-form-item>
                <!--如果任务要求角色是员工或者合作社成员,则用select下拉多选,如果是农民，则用树形结构-->
                <el-form-item
                        v-if="task.roleGroup!=4&&(template.templateSort&&template.templateSort.value!='FIXED')"
                        label="人员"
                        :label-width="labelWidth"
                        prop="userIds"
                >
                    <el-select
                            v-model="task.userIds"
                            multiple
                            placeholder="请选择任务人员"
                    >
                        <el-option
                                v-for="item in users"
                                :key="item.id"
                                :label="item.realName"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                        label="运输农资" v-if="template.taskType&&template.taskType.value=='DELIVERY'"
                        :label-width="labelWidth"
                        prop="materielIds">
                    <el-select
                            v-model="task.materielIds"
                            multiple
                            placeholder="请选择运输的农资"
                    >
                        <el-option
                                v-for="item in materiels"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="农户筛选条件"
                              v-if="task.roleGroup==4||(template.templateSort&&template.templateSort.value=='FIXED')"
                              :label-width="labelWidth">
                    <el-radio v-model="searchRadio" label="1" @change="radioChange">按合作社</el-radio>
                    <el-radio v-model="searchRadio" label="2" @change="radioChange">按区域</el-radio>
                </el-form-item>
                <el-form-item
                        label="选择农户"
                        v-if="(task.roleGroup==4||(template.templateSort&&template.templateSort.value=='FIXED'))&&searchRadio==='1'"
                        :label-width="labelWidth"
                        prop="userIds"
                >
                    <el-tree
                            :data="farmers"
                            show-checkbox
                            lazy
                            :load="loadTreeNode"
                            node-key="id"
                            ref="tree"
                            :props="defaultProps"
                            highlight-current
                            @check-change="check"
                    />
                </el-form-item>
                <el-form-item label="选择区域"
                              v-if="(task.roleGroup==4||(template.templateSort&&template.templateSort.value=='FIXED'))&&searchRadio==='2'"
                              :label-width="labelWidth">
                    <el-cascader
                            :options="areas"
                            v-model="area"
                            change-on-select
                            placeholder="请选择区域信息"
                            @change="areaChange"
                            @visible-change=areaVisibleChange
                    ></el-cascader>
                </el-form-item>
                <el-form-item label="选择农户"
                              v-show="(task.roleGroup==4||(template.templateSort&&template.templateSort.value=='FIXED'))&&searchRadio==='2'"
                              :label-width="labelWidth" prop="userIds">
                    <el-tree
                            :data="farmers"
                            show-checkbox
                            :load="loadFarmerNode"
                            node-key="id"
                            ref="farmerTree"
                            highlight-current
                            :props="areaFarmerProps"
                    />
                </el-form-item>
                <el-form-item
                        label="任务执行时间"
                        :label-width="labelWidth"
                        prop="rangTime"
                >
                    <el-date-picker
                            v-model="task.rangTime"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span
                    slot="footer"
                    class="dialog-footer"
            >
        <el-button
                size="small"
                @click="cancle('taskForm')"
        >取 消</el-button>
        <el-button
                size="small"
                type="primary"
                @click="submit('taskForm')"
        >确 定</el-button>
      </span>
        </el-dialog>
    </section>
</template>
<style>
</style>
<script>
    import {mapState} from "vuex";

    export default {
        name: "AddAndEdit",
        data() {
            return {
                searchRadio: '1',
                visible: false,
                labelWidth: "100px",
                users: [],
                farmers: [],
                checkFarmers: [],
                areas: [],
                area: [],
                defaultCheckedCode: [],
                defaultProps: {
                    children: "children",
                    label: "name",
                    isLeaf: 'leaf'
                },
                areaFarmerProps: {
                    children: "children",
                    label: "name",
                    isLeaf: 'leaf'
                },
                role: '',
                roles: [],
                groups: [],
                materiels: [],
                template: {
                    id: 0,
                    roleId: ''
                },
                task: {
                    userIds: [],
                    startTime: '',
                    endTime: '',
                    rangTime: '',
                    templateId: 0,
                    roleGroup: '',
                    materielIds: []
                },
                rules: {
                    userIds: [{required: true, message: "请选择人员", trigger: "blur"}],
                    roleGroup: [{required: true, message: "请选择角色分组", trigger: "blur"}],
                    startTime: [{required: true, message: "请选择开始时间", trigger: "blur"}],
                    rangTime: [{required: true, message: "请选择执行时间", trigger: "blur"}],
                    endTime: [{required: true, message: "请选择结束时间", trigger: "blur"}]
                }
            };
        },
        computed: {
            ...mapState({
                codebooks: state => state.codebooks.codebooks
            })
        },
        watch: {
            value: {
                deep: true,
                immediate: true,
                handler: function (val) {
                    this.visible = val.show;
                    this.labelWidth = val.formLabelWidth || "120px";
                    this.template = val.template;
                    this.load();
                }
            },
            visible(val) {
                if (!val) this.$emit("on-show-change", this.$data);
            }
        },
        mounted() {
            this.roles = this.codebooks ? this.codebooks.installedRoles : [];
            this.roles.forEach(item => {
                let obj = {
                    groupId: item.group,
                    groupName: item.groupName
                }
                if (obj.groupId != 1 && obj.groupId != 2 && this.checkRoleGroup(obj)) {
                    this.groups.push(obj);
                }
            })
            this.loadMateriel();
        },
        methods: {
            checkRoleGroup(obj) {
                for (let i in this.groups) {
                    if (this.groups[i].groupId == obj.groupId) {
                        return false;
                    }
                }
                return true;
            },
            loadMateriel() {
                this.$api.materiel.all("ALL", result => {
                    this.materiels = result.materiels;
                })
            },
            cancle(formName) {
                this.visible = false;
                this.task = {
                    userIds: [],
                    startTime: '',
                    endTime: '',
                    materielIds: []
                };
                this.users = [];
                this.area = [];
                this.areas = [];
                this.searchRadio = '1';
                this.$refs[formName].clearValidate();
                //this.farmers = [];
                this.$refs.tree?this.$refs.tree.setCheckedNodes([]):'';
            },
            check(node) {
                console.log(node);
            },
            loadFarmerNode() {
                this.$api.farmer.getFarmersByAreaCode(this.area[this.area.length - 1], this.area.length, result => {
                    let farmers = result.farmers.map(item => {
                        return {id: item.userId, name: item.name, leaf: true, type: 'farmer'}
                    })
                    let farmer = {id: '1', name: farmers.length > 0 ? '请选择农户' : '暂无农户', children: farmers};
                    this.farmers = [];
                    this.farmers.push(farmer);
                    //resolve(farmers);
                })
            },
            loadTreeNode(node, resolve) {
                console.log('1111', node);
                if (node.level === 0) {
                    //获取合作社
                    this.$api.cooperative.all(result => {
                        this.farmers = result.cooperatives;
                        this.farmers = this.farmers.map(item => {
                            return {id: item.id, name: item.name, children: [], type: 'coop'}
                        })
                        resolve(this.farmers);
                    })
                } else {
                    //获取农民
                    let parentId = node.data.id;
                    this.$api.cooperative.getReceiveTaskFarmers(parentId, this.template.id, result => {
                        let farmers = result.farmers;
                        farmers = farmers.map(item => {
                            return {id: item.userId, name: item.name, leaf: true, type: 'farmer'}
                        })
                        if(farmers.length===0&&node.data.type==='coop'){
                            this.$message.error("该合作社下没有农户");
                            this.$refs.tree.setChecked(node, false);
                        }
                        resolve(farmers);
                    })
                }
            },
            load() {
                if (this.template && this.template.roleId) {
                    this.$api.role.detail(this.template.roleId, result => {
                        this.role = result.role;
                        if (this.task.roleGroup != 4) {
                            this.loadData(this.task.roleGroup);
                        }
                    })
                }
            },
            groupChange(val) {
                console.log(val);
                if (this.task.roleGroup != 4) {
                    this.loadData();
                }
            },
            loadData() {
                this.$api.user.getReceiveTaskUsers(this.task.roleGroup, this.template.id, result => {
                    this.users = result.users;
                })
            },
            checkDate(startTime, endTime) {
                startTime = startTime.replace("-", "/");
                endTime = endTime.replace("-", "/");
                let startDate = new Date(Date.parse(startTime));
                let endDate = new Date(Date.parse(endTime));
                let templateStartDate = new Date(Date.parse(this.template.startTime.replace("-", "/")));
                let templateEndDate = new Date(Date.parse(this.template.endTime.replace("-", "/")));
                if (startDate < templateStartDate) {
                    console.log(startDate, templateStartDate);
                    this.$message.error("任务开始时间不能小于任务模板开始时间");
                    return false;
                }
                if (endDate > templateEndDate) {
                    this.$message.error("任务结束时间不能大于任务模板结束时间");
                    return false;
                }
                return true;
            },
            submit(formName) {
                if (this.template.taskType.value == 'FARMING') {
                    this.task.userIds = [];
                    let checkedNodes = this.searchRadio === '1' ? this.$refs.tree.getCheckedNodes() : this.$refs.farmerTree.getCheckedNodes();
                    if (checkedNodes.length > 0) {
                        checkedNodes.forEach(item => {
                            if (item.type == 'farmer') {
                                this.task.userIds.push(item.id);
                            }
                        })
                    }
                }
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        this.task.startTime = this.task.rangTime[0];
                        this.task.endTime = this.task.rangTime[1];
                        if (!(this.checkDate(this.task.startTime, this.task.endTime))) {
                            return;
                        }
                        const callback = () => {
                            this.cancle(formName);
                        };
                        if (this.template.templateSort && this.template.templateSort.value === 'FIXED') {
                            this.task.roleGroup = 4;
                        }
                        console.log('入参', this.task);
                        this.task.templateId = this.template.id;
                        this.$api.template.publish(this.task, callback)
                    } else {
                        return false;
                    }
                });
            },
            areaVisibleChange(val) {
                if (!val && this.area.length > 0) {
                    this.loadFarmerNode();
                }
            },
            areaChange(val) {
                let parentCode = '';
                if (val) {
                    parentCode = val[val.length - 1];
                } else {
                    parentCode = val;
                }
                this.$api.common.getAreaByParentCode(parentCode, result => {
                    if (!val) {
                        this.areas = result.areas;
                    } else {
                        result.areas = result.areas.map(item => {
                            if (item.areaLevel.value === "VILLAGE") {
                                return {
                                    value: item.value,
                                    label: item.label,
                                    parentCode: item.parentCode,
                                    areaLevel: item.areaLevel
                                }
                            } else {
                                return item;
                            }
                        })
                        this.pickChild(this.areas, parentCode, result.areas, val.length);
                    }
                })
            },
            pickChild(orgArea, parentCode, childArea, deep) {
                if (orgArea) {
                    orgArea.forEach(item => {
                        if (item.value === parentCode) {
                            item.children = childArea;
                        } else {
                            this.pickChild(item.children, parentCode, childArea, deep--);
                        }
                    });
                }
            },
            radioChange(val) {
                this.farmers = [];
                this.area = [];
                this.areas = [];
                this.task.userIds = [];
                if (val === '2') {
                    this.areaChange('');
                }
            }
        },
        props: {
            value: {
                type: Object,
                default: function () {
                    return {
                        show: false,
                        formLabelWidth: "150px",
                        template: {
                            id: 0
                        }
                    };
                }
            }
        }
    };
</script>
